<?php

namespace App\Http\Traits;

// use Intervention\Image\Facades\Image;

trait UploaderTrait
{
    protected $instance = null;
    protected $disk = 'public';
    protected $dirname = 'uploads';
    protected $filename = 'file';
    protected $imageExt = ['jpg', 'png', 'jpeg'];

    public function uploader()
    {
        $this->instance = request()->file($this->filename);
        return is_array($this->instance) ? $this->batch() : $this->save($this->instance);
    }

    /**
     * 保存文件
     *
     * @param \Illuminate\Http\UploadedFile $file
     * @return array
     */
    public function save($file): array
    {
        $name = $this->getSaveName(request()->input('original', ''), $this->getExtension($file));
        return [
            'size' => $this->formatSize($file->getSize()),
            'name' => $file->getClientOriginalName(),
            'url' => asset('storage/' . $file->storeAs($this->dirname . DIRECTORY_SEPARATOR . date('Ym'), $name, $this->disk)),
        ];
    }

    public function batch(): array
    {
        $res = [];
        foreach ($this->instance as $file) {
            $res[] = $this->save($file);
        }
        return $res;
    }

    public function formatSize($size): string
    {
        $units = ['B', 'KB', 'MB', 'GB', 'TB', 'PB'];
        $i = 0;
        while ($size > 1024) {
            $size /= 1024;
            $i++;
        }
        return round($size, 2) . '' . $units[$i];
    }

    protected function getSaveName(string $filename = '', string $extension = ''): string
    {
        if ($filename) {
            return $filename;
        }
        return sprintf('%s%s.%s', time(), substr(microtime(), 2, 4), $extension);
    }

    /**
     * 获取文件扩展名
     *
     * @param \Illuminate\Http\UploadedFile $file
     * @return string
     */
    protected function getExtension($file): string
    {
        return in_array($file->getExtension(), $this->imageExt) ? 'jpg' : $file->getClientOriginalExtension();
    }

    /**
     * 生成缩略图
     *
     * @param string $photo
     * @return string
     */
    public function thumb(string $photo)
    {
        $photo = strstr($photo, 'storage');

        $photoArr = explode('/', $photo);
        $thumb = str_replace('.', '-thumb.', array_pop($photoArr));
        $path = implode('/', $photoArr);
        // $realPath = public_path($path);

        // $image = Image::make(public_path($photo));
        // $width = $image->width();
        // $height = $image->height();
        // // 取最小的值，为正方形边长
        // $width = $width <= $height ? $width : $height;
        // // 居中裁剪图片为正方形（1:1）
        // $image->fit($width, null, function ($constraint) {
        //     $constraint->upsize();
        // });

        // if ($width > 260) {
        //     // 按比例缩小至 260x260
        //     $image->resize(260, 260);
        // }

        // 保存缩略图
        // $image->save($realPath . '/' . $thumb);

        return asset($path . '/' . $thumb);
    }

    /**
     * 头像压缩
     *
     * @param string $photo
     * @return void
     */
    public function avatar(string $photo)
    {
        $photo = strstr($photo, 'storage');

        $photoArr = explode('/', $photo);
        $originalName = array_pop($photoArr);
        $thumb = str_replace('.', '-avatar.', $originalName);
        $path = implode('/', $photoArr);
        // $realPath = public_path($path);

        // $image = Image::make(public_path($photo));
        // $width = $image->width();
        // $height = $image->height();
        // // 取最小的值，为正方形边长
        // $width = $width <= $height ? $width : $height;
        // // 居中裁剪图片为正方形（1:1）
        // $image->fit($width, null, function ($constraint) {
        //     $constraint->upsize();
        // });
        // // 按比例缩小至 400x400
        // if ($width > 400) {
        //     $image->resize(400, 400);
        // }

        // // 保存缩略图
        // $image->save($realPath . '/' . $thumb);
        // // 删除原图
        // @unlink($realPath . '/' . $originalName);

        return asset($path . '/' . $thumb);
    }
}
